import React, { useContext, useEffect, useRef, useState } from 'react';
import {
  Button,
  Dropdown,
  Form,
  Grid,
  Menu,
  Message,
  Modal,
  Select,
  Space,
  Spin,
  Table,
  TableColumnProps,
  Tooltip,
} from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import { GlobalContext } from '@/context';
import styles from './style/index.module.less';
import { EnumsRes } from '@/api/interface';
import { Enums } from '@/api/modules';
import cs from 'classnames';
import {
  Actions,
  AssignedPerson,
  Transfers,
  orgOther,
} from '@/api/modules/violation';
import { AssignedPersonItem } from '@/api/interface/violation';
import useIsMountedRef from '@/utils/useIsMountedRef';
import ActionWrapper from '@/components/ActionWrapper';
import Status from '@/components/Status';
import { IconDown } from '@arco-design/web-react/icon';
import { useSelector } from 'react-redux';
import { GlobalState } from '@/store';
import ModalTitle from '@/components/ModalTitle';

const { Row, Col } = Grid;
const Option = Select.Option;
const { useForm } = Form;
function TableEdit({
  visible,
  list,
  onVisible,
  onRefresh,
}: {
  visible: boolean;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  list: Array<any>;
  onVisible: (violator: boolean) => void;
  onRefresh: () => void;
}) {
  const t = useLocale(locale);
  const { rtl, lang } = useContext(GlobalContext);
  const [loading, setLoading] = useState(false);
  const [form] = useForm();

  const [formData, setFormData] = useState<any>({ status: undefined });
  const onValuesChange = (value) => {
    setFormData((a) => ({ ...a, ...value }));
  };

  const onOk = (val: boolean) => {
    form.validate((errors, values) => {
      if (!errors) {
        setLoading(true);
        values.assignedPerson = values.assignedPersons;
        values.refNumbers = list.map((a) => a.refNumber);
        Actions(values)
          .then(() => {
            setLoading(false);
            onVisible(val);
            onRefresh();
            form.resetFields();
            Message.success(t['update.success']);
          })
          .catch(() => {
            form.resetFields();
            setLoading(false);
          });
      }
    });
  };
  const onCancel = (val: boolean) => {
    onVisible(val);
    form.resetFields();
  };

  const [enums, setEnums] = useState<{ [key: string]: EnumsRes[] }>({
    violationStatusEnums: [],
    violationTypeEnums: [],
    actionTakenEnums: [],
  });
  const getEnums = async () => {
    try {
      const enumData = await Promise.all([
        Enums({ type: 'ViolationStatusEnums' }),
        Enums({ type: 'ViolationInternalTypeEnums' }),
        Enums({ type: 'ActionTakenEnums' }),
      ]);
      if (isMountedRef.current) {
        setEnums({
          violationStatusEnums: enumData[0].data,
          violationTypeEnums: enumData[1].data,
          actionTakenEnums: enumData[2].data,
        });
      }
    } catch (e) {
      console.log(e);
    }
  };

  const [assignedPerson, setAssignedPerson] = useState<
    Array<AssignedPersonItem>
  >([]);
  const getAssignedPerson = () => {
    AssignedPerson({})
      .then((res) => {
        if (isMountedRef.current) {
          setAssignedPerson(res.data);
        }
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const [orgs, setOrgs] = useState([]);
  const getOrgs = async () => {
    try {
      const { data } = await orgOther({});
      if (isMountedRef.current) {
        setOrgs(data);
      }
    } catch (e) {}
  };

  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    if (visible) {
      getOrgs();
      getEnums();
      getAssignedPerson();
    }
  }, [visible]);

  const columns: TableColumnProps[] = [
    {
      title: t['searchTable.columns.number'],
      dataIndex: 'refNumber',
      width: 220,
      render: (a, b) => {
        return (
          <>
            <Status status={b.status?.key}></Status>
            {a}
          </>
        );
      },
    },
    {
      title: t['searchTable.columns.type'],
      dataIndex: 'violationType',
      width: 200,
      ellipsis: true,
      render: (a: any): JSX.Element => {
        return (
          <Tooltip content={a?.value[lang === 'en-US' ? 'en' : 'ar']}>
            <div className="ellipsis">
              {a?.value[lang === 'en-US' ? 'en' : 'ar']}
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: t['searchTable.columns.entityName'],
      dataIndex: 'emirateEntity',
      width: 160,

      render: (
        a: { [x: string]: any },
        b: { emirateEntityOther: any }
      ): JSX.Element => {
        return (
          <>
            {a ? a[lang === 'en-US' ? 'name' : 'nameAr'] : b.emirateEntityOther}
          </>
        );
      },
    },
    {
      title: t['searchTable.columns.desc'],
      dataIndex: 'violationDesc',
      ellipsis: true,
      render: (a: any): JSX.Element => {
        return (
          <Tooltip
            content={
              <div style={{ maxHeight: '50vh', overflow: 'auto' }}>{a}</div>
            }
          >
            <div className="ellipsis">{a}</div>
          </Tooltip>
        );
      },
    },
  ];

  const handleTo = (e) => {
    setLoading(true);

    Transfers({ ...e, refNumbers: list.map((a) => a.refNumber) })
      .then(() => {
        setLoading(false);
        onVisible(false);
        onRefresh();
        Message.success(t['update.success']);
      })
      .catch(() => {
        setLoading(false);
      });
  };
  const { userInfo } = useSelector((state: GlobalState) => state);
  const dropList = (
    <Menu
      onClickMenuItem={(key) =>
        handleTo({ sendLocal: true, localEmirate: key })
      }
    >
      {orgs.map((option) => (
        <Menu.Item key={option.id}>{option.name}</Menu.Item>
      ))}
    </Menu>
  );
  // 转单
  const sendTo = () => {
    // ADAA为地方机构，UAEAA为联邦机构
    return (
      <>
        {userInfo.orgName === 'UAEAA' || userInfo.orgName === 'SAI' ? (
          <Dropdown
            droplist={dropList}
            position="bl"
            triggerProps={{ autoAlignPopupWidth: true }}
          >
            <Button
              type="outline"
              className={styles['button']}
              loading={loading}
              loadingFixedWidth
            >
              {t['actions.sendTolocal']}
              <IconDown />
            </Button>
          </Dropdown>
        ) : (
          <Space>
            <Button
              type="outline"
              onClick={() => handleTo({ sendSAI: true })}
              loading={loading}
              loadingFixedWidth
            >
              {t['actions.sendToSAI']}
            </Button>
          </Space>
        )}
      </>
    );
  };
  return (
    <div>
      <Modal
        title={<ModalTitle title={t['tableEdit.title']} />}
        style={{ width: '960px' }}
        visible={visible}
        maskClosable={false}
        mountOnEnter={true}
        unmountOnExit={true}
        className={cs(rtl ? 'rtl' : '')}
        footer={
          <>
            {sendTo()}
            <Button
              type="primary"
              onClick={() => onOk(false)}
              loading={loading}
              loadingFixedWidth
            >
              {t['actions.save']}
            </Button>
          </>
        }
        // onOk={() => onOk(false)}
        onCancel={() => onCancel(false)}
      >
        <Spin
          loading={loading}
          className={cs(styles['spin'], rtl ? 'rtl' : '')}
          style={{ width: '100%' }}
        >
          <Form
            form={form}
            labelAlign="left"
            labelCol={{ span: 0 }}
            wrapperCol={{ span: 24 }}
            onValuesChange={onValuesChange}
            autoComplete="off"
          >
            <Row gutter={24}>
              <ActionWrapper action="violation.detail.assignedperson">
                <Col span={12}>
                  <Form.Item
                    // label={t['searchTable.columns.person']}
                    field="assignedPersons"
                  >
                    <Select
                      allowClear
                      showSearch
                      mode="multiple"
                      maxTagCount={4}
                      placeholder={t['searchTable.columns.person.placeholder']}
                      triggerProps={{
                        autoAlignPopupWidth: false,
                        autoAlignPopupMinWidth: true,
                      }}
                      filterOption={(inputValue, option) =>
                        option.props.children
                          .toLowerCase()
                          .indexOf(inputValue.toLowerCase()) >= 0
                      }
                    >
                      {assignedPerson.map((option, index) => (
                        <Option key={index} value={option.id}>
                          {`${option.name}(${option.count})`}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </ActionWrapper>
              <ActionWrapper action="violation.detail.classifyviolationtype">
                <Col span={12}>
                  <Form.Item
                    // label={t['searchTable.columns.boxType']}
                    field="violationType"
                  >
                    <Select
                      maxTagCount={1}
                      mode="multiple"
                      allowClear
                      showSearch
                      placeholder={t['searchTable.columns.boxType.placeholder']}
                      triggerProps={{
                        autoAlignPopupWidth: false,
                        autoAlignPopupMinWidth: true,
                      }}
                      filterOption={(inputValue, option) => {
                        return (
                          option.props.children
                            .toLowerCase()
                            .indexOf(inputValue.toLowerCase()) >= 0
                        );
                      }}
                    >
                      {enums.violationTypeEnums.map((option, index) => (
                        <Option key={index} value={option.key}>
                          {option.value[lang === 'en-US' ? 'en' : 'ar']}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </ActionWrapper>
              <ActionWrapper action="violation.detail.violationstatus">
                <Col span={12}>
                  <Form.Item
                    // label={t['searchTable.columns.status']}
                    field="status"
                  >
                    <Select
                      placeholder={t['searchTable.columns.status.placeholder']}
                      triggerProps={{
                        autoAlignPopupWidth: false,
                        autoAlignPopupMinWidth: true,
                      }}
                      onChange={() => {
                        form.setFieldsValue({
                          actionTaken: undefined,
                        });
                      }}
                    >
                      {enums.violationStatusEnums.map((option, index) => (
                        <Option key={index} value={option.key}>
                          <div className={rtl && 'rtl'}>
                            <Status status={option?.key}></Status>
                            {option.value[lang === 'en-US' ? 'en' : 'ar']}
                          </div>
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </ActionWrapper>

              <ActionWrapper action="violation.detail.actiontaken">
                <Col span={12}>
                  <Form.Item
                    // label={t['searchTable.columns.taken']}
                    field="actionTaken"
                  >
                    <Select
                      allowClear
                      placeholder={t['searchTable.columns.taken.placeholder']}
                      triggerProps={{
                        autoAlignPopupWidth: false,
                        autoAlignPopupMinWidth: true,
                      }}
                    >
                      {enums.actionTakenEnums
                        .filter(
                          (a) =>
                            a.key.charAt(0).toUpperCase() ===
                            (formData?.status &&
                              formData?.status.charAt(0).toUpperCase())
                        )
                        .map((option, index) => (
                          <Option key={index} value={option.key}>
                            {option.value[lang === 'en-US' ? 'en' : 'ar']}
                          </Option>
                        ))}
                    </Select>
                  </Form.Item>
                </Col>
              </ActionWrapper>
            </Row>
          </Form>
          <div>
            <Table
              border={{
                wrapper: true,
                cell: true,
              }}
              scroll={{
                y: '55vh',
              }}
              columns={columns}
              data={list}
              pagination={false}
              rowKey="refNumber"
              rowClassName={(a) => {
                return a?.status?.key;
              }}
            ></Table>
          </div>
        </Spin>
      </Modal>
    </div>
  );
}

export default TableEdit;
